/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue';
import Router from 'vue-router';
import http from '@/utils/httpRequest';
import { clearLoginInfo } from '@/utils';
import valid from '@/utils/validate';
Vue.use(Router);

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV);

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  {
    path: '/404',
    component: _import('common/404'),
    name: '404',
    meta: { title: '404未找到' },
  },
  {
    path: '/login',
    component: _import('common/login'),
    name: 'login',
    meta: { title: '登录' },
  },
];

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: _import('main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    // serve路由
    {
      path: '/generator-coretable',
      component: _import('modules/serve/generator-coretable'),
      name: 'generator-coretable',
      meta: { title: 'Table管理', isTab: true },
    },
    {
      path: '/insert-data',
      component: _import('modules/serve/insert-data'),
      name: 'insert-data',
      meta: { title: '插入数据', isTab: true },
    },
    {
      path: '/home',
      component: _import('common/home'),
      name: 'home',
      meta: { title: '首页' },
    },
    {
      path: '/theme',
      component: _import('common/theme'),
      name: 'theme',
      meta: { title: '主题' },
    },
    {
      path: '/tech-workbench',
      component: _import('modules/user/workbench/index'),
      name: 'tech-workbench',
      meta: { title: '学管工作台', isTab: true },
    },
    {
      path: '/demo-echarts',
      component: _import('demo/echarts'),
      name: 'demo-echarts',
      meta: { title: 'demo-echarts', isTab: true },
    },
    {
      path: '/demo-ueditor',
      component: _import('demo/ueditor'),
      name: 'demo-ueditor',
      meta: { title: 'demo-ueditor', isTab: true },
    },

    //考试管理
    {
      path: '/exam',
      component: _import('modules/exam/exam/index'),
      name: 'exam',
      meta: { title: '考试管理', isTab: true },
    },
    {
      path: '/examDetail/:id',
      component: _import('modules/exam/exam/details'),
      name: 'examDetail',
      meta: { title: '考试详情', isTab: true },
    },

    // 订单管理
    {
      path: '/order-details',
      component: _import('modules/order/order-list/order-details'),
      name: 'order-details',
      meta: { title: '订单详情', isTab: true },
    },
    {
      path: '/integralOrderList',
      component: _import('modules/order/integralOrder/index'),
      name: 'integralOrderList',
      meta: { title: '积分订单', isTab: true },
    },
    {
      path: '/integral-order-details',
      component: _import('modules/order/integralOrder/details'),
      name: 'integral-order-details',
      meta: { title: '积分订单详情', isTab: true },
    },

    // 课程管理
    {
      path: '/add-update-class',
      component: _import('modules/course/class-list/add-update-class'),
      name: 'add-update-class',
      meta: { title: '课程（新增 / 编辑）', isTab: true },
    },
    {
      path: '/class-hour',
      component: _import('modules/course/class-list/class-hour'),
      name: 'class-hour',
      meta: { title: '课时设置', isTab: true },
    },
    {
      path: '/class-hour-details',
      component: _import('modules/course/class-list/class-hour-details'),
      name: 'class-hour-details',
      meta: { title: '课件预览', isTab: true },
    },
    {
      path: '/course-term',
      component: _import('modules/course/class-list/course-term'),
      name: 'course-term',
      meta: { title: '课期管理', isTab: true },
    },
    {
      path: '/add-update-course-term',
      component: _import('modules/course/class-list/add-update-course-term'),
      name: 'add-update-course-term',
      meta: { title: '课期（新增 / 编辑）', isTab: true },
    },
    {
      path: '/selected-topic',
      component: _import('modules/course/class-list/selected-topic'),
      name: 'selected-topic',
      meta: { title: '选题', isTab: false },
    },
    {
      path: '/basestation',
      component: _import('modules/nice-config/basestation/index'),
      name: 'basestation',
      meta: { title: '答题器基站管理', isTab: true },
    },
    // 商品管理
    {
      path: '/add-goods',
      component: _import('modules/goods/course-management/add-goods'),
      name: 'add-goods',
      meta: { title: '商品（新增 / 编辑）', isTab: true },
    },
    {
      path: '/add-material-object',
      component: _import(
        'modules/goods/entity-administration/add-material-object'
      ),
      name: 'add-material-object',
      meta: { title: '新增实物', isTab: true },
    },
    // 订单管理
    {
      path: '/order-details',
      component: _import('modules/order/order-list/order-details'),
      name: 'order-details',
      meta: { title: '订单详情', isTab: true },
    },
    // 用户管理
    {
      path: '/student-detail/:id',
      component: _import('modules/user/students-administration/studentDetail'),
      name: 'student-detail',
      meta: { title: '学生详情', isTab: true },
    },
    {
      path: '/period-students/:id',
      component: _import('modules/user/course-students/periodDetail'),
      name: 'period-students',
      meta: { title: '期次班级列表', isTab: true },
    },
    {
      path: '/school-detail/:id',
      component: _import('modules/user/school-list/schoolDetail'),
      name: 'school-detail',
      meta: { title: '学校详情', isTab: true },
    },
    {
      path: '/base-station-detail',
      component: _import('modules/user/school-list/baseStationDetail'),
      name: 'base-station-detail',
      meta: { title: '基站详情', isTab: true },
    },
    {
      path: '/staff-detail/:id',
      component: _import('modules/user/staff-administration/staffDetail'),
      name: 'staff-detail',
      meta: { title: '员工详情', isTab: true },
    },
    {
      path: '/add-banner',
      component: _import('modules/app-set/banner-set/add-banner'),
      name: 'add-banner',
      meta: { title: 'Banner（添加 / 修改）', isTab: true },
    },
    {
      path: '/school-banner',
      component: _import('modules/user/school-banner/index'),
      name: 'school-banner',
      meta: { title: '学校Banner', isTab: true },
    },
    {
      path: '/school-timetable',
      component: _import('modules/user/school-timetable/index'),
      name: 'school-timetable',
      meta: { title: '课表', isTab: true },
    },
    // launch管理
    {
      path: '/launch-app-detail',
      component: _import('modules/launch/launch-manage/launch-app-detail'),
      name: 'launch-app-detail',
      meta: { title: 'Launch-App详情', isTab: true },
    },
    {
      path: '/launch-school-detail',
      component: _import('modules/launch/launch-school/school-detail'),
      name: 'launch-school-detail',
      meta: { title: 'Launch-学校详情', isTab: true },
    },

    // 营销中心
    {
      path: '/add-coupon',
      component: _import('modules/marketing/coupon/add-coupon'),
      name: 'add-coupon',
      meta: { title: '优惠券（新增 / 编辑）', isTab: true },
    },
    {
      path: '/add-activity',
      component: _import('modules/marketing/activity/add-activity'),
      name: 'add-activity',
      meta: { title: '新增活动', isTab: true },
    },
    // 数据中心
    {
      path: '/operate-center/market/school-list-info',
      component: _import('modules/operate-center/market/school-list-info'),
      name: 'operate-center/market/school-list-info',
      meta: { title: '市场-学校详情', isTab: true },
    },
  ],
  beforeEnter(to, from, next) {
    let token = Vue.cookie.get('token');
    if (!token || !/\S/.test(token)) {
      clearLoginInfo();
      next({ name: 'login' });
    }
    next();
  },
};

const children = [
  // 课程管理
  {
    path: '/class-list',
    component: _import('modules/course/class-list/index'),
    name: 'class-list',
    meta: { title: '课程列表', isTab: true },
  },
  {
    path: '/class-price',
    component: _import('modules/course/class-price/index'),
    name: 'class-price',
    meta: { title: '课时定价', isTab: true },
  },

  // 商品管理
  {
    path: '/course-management',
    component: _import('modules/goods/course-management/index'),
    name: 'course-management',
    meta: { title: '课程管理', isTab: true },
  },
  {
    path: '/entity-administration',
    component: _import('modules/goods/entity-administration/index'),
    name: 'entity-administration',
    meta: { title: '实物管理', isTab: true },
  },
  {
    path: '/norms-administration',
    component: _import('modules/goods/norms-administration/index'),
    name: 'norms-administration',
    meta: { title: '规格管理', isTab: true },
  },

  // 订单管理
  {
    path: '/order-list',
    component: _import('modules/order/order-list/index'),
    name: 'order-list',
    meta: { title: '订单列表', isTab: true },
  },
  {
    path: '/refund-administration',
    component: _import('modules/order/refund-administration/index'),
    name: 'refund-administration',
    meta: { title: '退款管理', isTab: true },
  },

  // 用户管理
  {
    path: '/students-administration',
    component: _import('modules/user/students-administration/index'),
    name: 'students-administration',
    meta: { title: '学生管理', isTab: true },
  },
  {
    path: '/allocation-guidance',
    component: _import('modules/user/allocation-guidance/index'),
    name: 'allocation-guidance',
    meta: { title: '分配辅导', isTab: true },
  },
  {
    path: '/class-assignment',
    component: _import('modules/user/class-assignment/index'),
    name: 'class-assignment',
    meta: { title: '分班管理', isTab: true },
  },
  {
    path: '/course-students',
    component: _import('modules/user/course-students/index'),
    name: 'course-students',
    meta: { title: '课程学生', isTab: true },
  },
  {
    path: '/school-list',
    component: _import('modules/user/school-list/index'),
    name: 'school-list',
    meta: { title: '学校列表', isTab: true },
  },
  {
    path: '/staff-administration',
    component: _import('modules/user/staff-administration/index'),
    name: 'staff-administration',
    meta: { title: '员工管理', isTab: true },
  },
  {
    path: '/job-administration',
    component: _import('modules/user/job-administration/index'),
    name: 'job-administration',
    meta: { title: '岗位管理', isTab: true },
  },
  {
    path: '/organize-structure',
    component: _import('modules/user/organize-structure/index'),
    name: 'organize-structure',
    meta: { title: '组织架构', isTab: true },
  },
  {
    path: '/user-power',
    component: _import('modules/user/user-power/index'),
    name: 'user-power',
    meta: { title: '角色管理', isTab: true },
  },
  // nice系统配置
  {
    path: '/tree',
    component: _import('modules/nice-config/tree/index'),
    name: 'tree',
    meta: { title: '枚举配置', isTab: true },
  },
  {
    path: '/config-router',
    component: _import('modules/nice-config/config-router/index'),
    name: 'config-router',
    meta: { title: '路由配置', isTab: true },
  },
  {
    path: '/power-config',
    component: _import('modules/nice-config/power-config/index'),
    name: 'power-config',
    meta: { title: '权限配置', isTab: true },
  },
  {
    path: '/project-config-tree',
    component: _import('modules/nice-config/project-config-tree/index'),
    name: 'project-config-tree',
    meta: { title: '系统配置', isTab: true },
  },
  {
    path: '/nice-ol-router',
    component: _import('modules/nice-config/nice-ol-router/index'),
    name: 'nice-ol-router',
    meta: { title: '海亮网校路由配置', isTab: true },
  },
  {
    path: '/nice-route-power',
    component: _import('modules/nice-config/nice-route-power/index'),
    name: 'nice-route-power',
    meta: { title: '接口权限配置', isTab: true },
  },
  {
    path: '/btn-config-tree',
    component: _import('modules/nice-config/btn-config-tree/index'),
    name: 'btn-config-tree',
    meta: { title: '按钮配置', isTab: true },
  },

  // launch管理
  {
    path: '/launch-manage',
    component: _import('modules/launch/launch-manage/index'),
    name: 'launch-manage',
    meta: { title: 'launch管理', isTab: true },
  },
  {
    path: '/launch-app',
    component: _import('modules/launch/launch-manage/launch-app'),
    name: 'launch-app',
    meta: { title: 'Launch-App管理', isTab: true },
  },
  {
    path: '/launch-manage-stu',
    component: _import('modules/launch/launch-manage/index-stu'),
    name: 'launch-manage-stu',
    meta: { title: 'launch管理', isTab: true },
  },
  {
    path: '/launch-app-stu',
    component: _import('modules/launch/launch-manage/launch-app-stu'),
    name: 'launch-app-stu',
    meta: { title: 'Launch-App管理', isTab: true },
  },
  {
    path: '/launch-school',
    component: _import('modules/launch/launch-school/index'),
    name: 'launch-school',
    meta: { title: '', isTab: true },
  },

  // 营销中心
  {
    path: '/coupon',
    component: _import('modules/marketing/coupon/index'),
    name: 'coupon',
    meta: { title: '优惠券管理', isTab: true },
  },

  // 领课标签
  {
    path: '/leading-class',
    component: _import('modules/leading-class/index'),
    name: 'leading-class',
    meta: { title: '领课系统' },
  },
  // 举报管理
  {
    path: '/report',
    component: _import('modules/report/index'),
    name: 'report',
    meta: { title: '举报管理', isTab: true },
  },
  // 活动列表
  {
    path: '/activity',
    component: _import('modules/marketing/activity/index'),
    name: 'activity',
    meta: { title: '活动列表', isTab: true },
  },
  // APP管理
  {
    path: '/banner-set',
    component: _import('modules/app-set/banner-set/index'),
    name: 'banner-set',
    meta: { title: 'banner管理', isTab: true },
  },
  // 评价管理
  {
    path: '/comment-management',
    component: _import('modules/comment/index'),
    name: 'comment-management',
    meta: { title: '评价管理', isTab: true },
  },
  // 工具目录
  {
    path: '/batch-signup-change',
    component: _import('modules/tools/batchSignupChange'),
    name: 'batch-signup-change',
    meta: { title: '批量报课', isTab: true },
  },
  {
    path: '/batch-teach-change',
    component: _import('modules/tools/batchTeachChange'),
    name: 'batch-teach-change',
    meta: { title: '批量更改辅导老师', isTab: true },
  },
  {
    path: '/roll-back-student-course',
    component: _import('modules/tools/rollbackStudentCourse'),
    name: 'roll-back-student-course',
    meta: { title: '回滚学生课程', isTab: true },
  },
  // 数据中心
  {
    path: '/operate-center/learning-management-statistics',
    component: _import('modules/operate-center/learning-management-statistics'),
    name: 'operate-center/learning-management-statistics',
    meta: { title: '学管统计', isTab: true },
  },
  {
    path: '/operate-center/market/index',
    component: _import('modules/operate-center/market/index'),
    name: 'operate-center/market/index',
    meta: { title: '市场-总数据', isTab: true },
  },
  {
    path: '/operate-center/market/school-list',
    component: _import('modules/operate-center/market/school-list'),
    name: 'operate-center/market/school-list',
    meta: { title: '市场-学校列表', isTab: true },
  },
];

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes),
});

router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  if (
    router.options.isAddDynamicMenuRoutes ||
    fnCurrentRouteType(to, globalRoutes) === 'global'
  ) {
    next();
  } else {
    http({
      // url: http.adornUrl('/usercenter/sys/menu/nav'),
      url: http.adornUrl('/usercenter/operation/role/getOwnMenu'),
      method: 'post',
      data: {},
    })
      .then(({ data }) => {
        if (data && data.code === 0) {
          let menuList = JSON.parse(
            JSON.stringify(data.data)
              .split('menu_id')
              .join('menuId')
              .split('parent_id')
              .join('parentId')
              .split('child')
              .join('list')
          );
          fnAddDynamicMenuRoutes(menuList);
          router.options.isAddDynamicMenuRoutes = true;
          sessionStorage.setItem('menuList', JSON.stringify(menuList || '[]'));
          // sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]')) //后续对接按钮权限时使用
          next({ ...to, replace: true });
        } else {
          sessionStorage.setItem('menuList', '[]');
          // sessionStorage.setItem('permissions', '[]')//后续对接按钮权限时使用
          next();
        }
      })
      .catch((e) => {
        console.log(
          `%c${e} 请求菜单列表和权限失败，跳转至登录页！！`,
          'color:blue'
        );
        router.push({ name: 'login' });
      });
  }
});

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
  var temp = [];
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global';
    } else if (
      globalRoutes[i].children &&
      globalRoutes[i].children.length >= 1
    ) {
      temp = temp.concat(globalRoutes[i].children);
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main';
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = [];
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list);
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '');
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: '',
        },
      };
      // url以http[s]://开头, 通过iframe展示
      if (valid.isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`;
        route['name'] = `i-${menuList[i].menuId}`;
        route['meta']['iframeUrl'] = menuList[i].url;
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`) || null;
        } catch (e) {}
      }
      routes.push(route);
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes);
  } else {
    mainRoutes.name = 'main-dynamic';
    children.forEach((child) => {
      routes.forEach((route) => {
        if (route.name === child.name) {
          route['component'] = child['component'];
        }
      });
    });
    mainRoutes.children = routes;
    router.addRoutes([mainRoutes, { path: '*', redirect: { name: '404' } }]);
    sessionStorage.setItem(
      'dynamicMenuRoutes',
      JSON.stringify(mainRoutes.children || '[]')
    );
    console.log('\n');
    console.log(
      '%c!<-------------------- 动态(菜单)路由 s -------------------->',
      'color:blue'
    );
    console.log(mainRoutes.children);
    console.log(
      '%c!<-------------------- 动态(菜单)路由 e -------------------->',
      'color:blue'
    );
  }
}
console.log('router===>', router);
export default router;
